<template>
  <div class="merchant-rating">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>酒店评分与信用管理</span>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="酒店名称">
          <el-input v-model="searchForm.name" placeholder="请输入酒店名称" />
        </el-form-item>
        <el-form-item label="酒店类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择酒店类型"
            clearable
          >
            <el-option label="经济型" value="budget" />
            <el-option label="商务型" value="business" />
            <el-option label="豪华型" value="luxury" />
            <el-option label="度假型" value="resort" />
          </el-select>
        </el-form-item>
        <el-form-item label="信用等级">
          <el-select
            v-model="searchForm.creditLevel"
            placeholder="请选择信用等级"
            clearable
          >
            <el-option label="优秀" value="excellent" />
            <el-option label="良好" value="good" />
            <el-option label="一般" value="normal" />
            <el-option label="较差" value="poor" />
            <el-option label="风险" value="risk" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 评分统计 -->
      <el-row :gutter="20" class="statistics-row">
        <el-col :span="6" v-for="(stat, index) in ratingStats" :key="index">
          <el-card class="statistics-card" shadow="hover">
            <div class="statistics-content">
              <div
                class="statistics-icon"
                :style="{ backgroundColor: stat.color }"
              >
                <i :class="stat.icon"></i>
              </div>
              <div class="statistics-info">
                <div class="label">{{ stat.label }}</div>
                <div class="value">{{ stat.value }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 酒店列表 -->
      <el-table :data="merchantList" border v-loading="loading">
        <template #header>
          <div class="table-header-operations">
            <el-button-group>
              <el-button
                :type="sortOrder === 'asc' ? 'primary' : 'default'"
                @click="toggleSortOrder('asc')"
                size="small"
              >
                正序
              </el-button>
              <el-button
                :type="sortOrder === 'desc' ? 'primary' : 'default'"
                @click="toggleSortOrder('desc')"
                size="small"
              >
                倒序
              </el-button>
            </el-button-group>
          </div>
        </template>
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无酒店评分数据" 
              :image-size="200"
            >
              <div class="empty-text">还没有酒店评分与信用记录</div>
              <div class="empty-subtext">酒店数据将在此处展示评分与信用信息</div>
            </el-empty>
          </div>
        </template>
        <el-table-column type="expand">
          <template #default="props">
            <el-form label-position="left" inline class="rating-detail">
              <el-form-item label="客房服务评分">
                <el-progress
                  :percentage="props.row.serviceScore"
                  :color="getScoreColor(props.row.serviceScore)"
                />
              </el-form-item>
              <el-form-item label="客房设施评分">
                <el-progress
                  :percentage="props.row.facilityScore"
                  :color="getScoreColor(props.row.facilityScore)"
                />
              </el-form-item>
              <el-form-item label="卫生清洁评分">
                <el-progress
                  :percentage="props.row.cleanScore"
                  :color="getScoreColor(props.row.cleanScore)"
                />
              </el-form-item>
              <el-form-item label="性价比评分">
                <el-progress
                  :percentage="props.row.priceScore"
                  :color="getScoreColor(props.row.priceScore)"
                />
              </el-form-item>
              <el-form-item label="客户满意度">
                <el-progress
                  :percentage="props.row.satisfactionRate"
                  :color="getScoreColor(props.row.satisfactionRate)"
                />
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="酒店名称" min-width="180" />
        <el-table-column prop="type" label="酒店类型" width="100">
          <template #default="scope">
            <el-tag :type="getMerchantTypeTag(scope.row.type)">
              {{ getMerchantTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="overallScore" label="综合评分" width="120">
          <template #default="scope">
            <el-rate
              v-model="scope.row.overallScore"
              disabled
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
        <el-table-column prop="creditScore" label="信用评分" width="120">
          <template #default="scope">
            <span
              :style="{ color: getCreditScoreColor(scope.row.creditScore) }"
            >
              {{ scope.row.creditScore }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="creditLevel" label="信用等级" width="100">
          <template #default="scope">
            <el-tag :type="getCreditLevelTag(scope.row.creditLevel)">
              {{ getCreditLevelLabel(scope.row.creditLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warningCount" label="警告次数" width="100" />
        <el-table-column prop="complaintRate" label="投诉率" width="100">
          <template #default="scope"> {{ scope.row.complaintRate }}% </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button type="primary" link @click="handleRating(scope.row)">
                评分调整
              </el-button>
              <el-button type="warning" link @click="handleWarning(scope.row)">
                发送警告
              </el-button>
              <el-button
                type="danger"
                link
                @click="handlePunishment(scope.row)"
              >
                处罚
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 评分调整对话框 -->
    <el-dialog
      v-model="ratingDialogVisible"
      title="评分调整"
      width="500px"
      :modal-append-to-body="true"
      :lock-scroll="true"
      :close-on-click-modal="false"
      class="rating-dialog"
      destroy-on-close
    >
      <el-scrollbar height="400px">
        <el-form
          ref="ratingFormRef"
          :model="ratingForm"
          :rules="ratingFormRules"
          label-width="100px"
        >
          <el-form-item label="客房服务评分" prop="serviceScore">
            <el-slider
              v-model="ratingForm.serviceScore"
              :max="100"
              :step="1"
              show-input
            />
          </el-form-item>
          <el-form-item label="客房设施评分" prop="facilityScore">
            <el-slider
              v-model="ratingForm.facilityScore"
              :max="100"
              :step="1"
              show-input
            />
          </el-form-item>
          <el-form-item label="卫生清洁评分" prop="cleanScore">
            <el-slider
              v-model="ratingForm.cleanScore"
              :max="100"
              :step="1"
              show-input
            />
          </el-form-item>
          <el-form-item label="性价比评分" prop="priceScore">
            <el-slider
              v-model="ratingForm.priceScore"
              :max="100"
              :step="1"
              show-input
            />
          </el-form-item>
          <el-form-item label="调整原因" prop="reason">
            <el-input
              type="textarea"
              v-model="ratingForm.reason"
              :rows="3"
              placeholder="请输入调整原因"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ratingDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRating">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 警告对话框 -->
    <el-dialog v-model="warningDialogVisible" title="发送警告" width="500px">
      <el-form
        ref="warningFormRef"
        :model="warningForm"
        :rules="warningFormRules"
        label-width="100px"
      >
        <el-form-item label="警告类型" prop="type">
          <el-select v-model="warningForm.type" placeholder="请选择警告类型">
            <el-option label="客房服务问题" value="room_service" />
            <el-option label="设施维护问题" value="facility" />
            <el-option label="卫生问题" value="hygiene" />
            <el-option label="价格问题" value="price" />
            <el-option label="虚假宣传" value="false_advertising" />
            <el-option label="安全隐患" value="safety" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="警告内容" prop="content">
          <el-input
            type="textarea"
            v-model="warningForm.content"
            :rows="4"
            placeholder="请输入警告内容"
          />
        </el-form-item>
        <el-form-item label="整改期限" prop="deadline">
          <el-date-picker
            v-model="warningForm.deadline"
            type="date"
            placeholder="请选择整改期限"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="warningDialogVisible = false">取消</el-button>
          <el-button type="warning" @click="submitWarning">发送警告</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 处罚对话框 -->
    <el-dialog v-model="punishmentDialogVisible" title="酒店处罚" width="500px">
      <el-form
        ref="punishmentFormRef"
        :model="punishmentForm"
        :rules="punishmentFormRules"
        label-width="100px"
      >
        <el-form-item label="处罚类型" prop="type">
          <el-select v-model="punishmentForm.type" placeholder="请选择处罚类型">
            <el-option label="警告" value="warning" />
            <el-option label="罚款" value="fine" />
            <el-option label="限制预订" value="booking_restriction" />
            <el-option label="暂停营业" value="suspension" />
            <el-option label="取消合作" value="termination" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="罚款金额"
          prop="amount"
          v-if="punishmentForm.type === 'fine'"
        >
          <el-input-number
            v-model="punishmentForm.amount"
            :min="0"
            :step="100"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item
          label="处罚期限"
          prop="duration"
          v-if="
            ['booking_restriction', 'suspension'].includes(punishmentForm.type)
          "
        >
          <el-input-number
            v-model="punishmentForm.duration"
            :min="1"
            :step="1"
            controls-position="right"
          >
            <template #suffix>天</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="处罚原因" prop="reason">
          <el-input
            type="textarea"
            v-model="punishmentForm.reason"
            :rows="4"
            placeholder="请输入处罚原因"
          />
        </el-form-item>
        <el-form-item label="处罚说明" prop="description">
          <el-input
            type="textarea"
            v-model="punishmentForm.description"
            :rows="4"
            placeholder="请输入处罚说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="punishmentDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="submitPunishment"
            >确定处罚</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "@/api/axios";
import * as XLSX from "xlsx";

// 搜索表单
const searchForm = reactive({
  name: "",
  type: "",
  creditLevel: "",
});

// 列表数据
const loading = ref(false);
const sortOrder = ref("desc");
const merchantList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 统计数据
const ratingStats = ref([
  {
    label: "平均评分",
    value: "4.5",
    icon: "fas fa-star",
    color: "#ffd700",
  },
  {
    label: "优秀酒店",
    value: "128",
    icon: "fas fa-crown",
    color: "#ff9900",
  },
  {
    label: "警告酒店",
    value: "12",
    icon: "fas fa-exclamation-triangle",
    color: "#ff4949",
  },
  {
    label: "待整改",
    value: "5",
    icon: "fas fa-tools",
    color: "#409eff",
  },
]);

// 评分相关
const ratingDialogVisible = ref(false);
const ratingFormRef = ref(null);
const ratingForm = reactive({
  serviceScore: 0,
  facilityScore: 0,
  cleanScore: 0,
  priceScore: 0,
  reason: "",
});

const ratingFormRules = {
  reason: [{ required: true, message: "请输入调整原因", trigger: "blur" }],
};

// 警告相关
const warningDialogVisible = ref(false);
const warningFormRef = ref(null);
const warningForm = reactive({
  type: "",
  content: "",
  deadline: "",
});

const warningFormRules = {
  type: [{ required: true, message: "请选择警告类型", trigger: "change" }],
  content: [{ required: true, message: "请输入警告内容", trigger: "blur" }],
  deadline: [{ required: true, message: "请选择整改期限", trigger: "change" }],
};

// 处罚相关
const punishmentDialogVisible = ref(false);
const punishmentFormRef = ref(null);
const punishmentForm = reactive({
  type: "",
  amount: 0,
  duration: 1,
  reason: "",
  description: "",
});

const punishmentFormRules = {
  type: [{ required: true, message: "请选择处罚类型", trigger: "change" }],
  amount: [{ required: true, message: "请输入罚款金额", trigger: "blur" }],
  duration: [{ required: true, message: "请输入处罚期限", trigger: "blur" }],
  reason: [{ required: true, message: "请输入处罚原因", trigger: "blur" }],
  description: [{ required: true, message: "请输入处罚说明", trigger: "blur" }],
};

// 当前操作的酒店
const currentHotel = ref(null);

// 测试数据
const mockData = [
  {
    id: 1,
    name: "桂林山水大酒店",
    type: "luxury",
    overallScore: 4.8,
    creditScore: 95,
    creditLevel: "excellent",
    warningCount: 0,
    complaintRate: 0.5,
    serviceScore: 96,
    facilityScore: 94,
    cleanScore: 98,
    priceScore: 92,
    satisfactionRate: 95,
  },
  {
    id: 2,
    name: "阳朔西街客栈",
    type: "budget",
    overallScore: 4.2,
    creditScore: 85,
    creditLevel: "good",
    warningCount: 1,
    complaintRate: 2.1,
    serviceScore: 86,
    facilityScore: 88,
    cleanScore: 82,
    priceScore: 90,
    satisfactionRate: 85,
  },
  {
    id: 3,
    name: "象山温泉度假酒店",
    type: "resort",
    overallScore: 4.5,
    creditScore: 88,
    creditLevel: "good",
    warningCount: 0,
    complaintRate: 1.2,
    serviceScore: 89,
    facilityScore: 87,
    cleanScore: 92,
    priceScore: 85,
    satisfactionRate: 90,
  },
  {
    id: 4,
    name: "桂林商务酒店",
    type: "business",
    overallScore: 3.5,
    creditScore: 65,
    creditLevel: "poor",
    warningCount: 3,
    complaintRate: 5.8,
    serviceScore: 65,
    facilityScore: 70,
    cleanScore: 75,
    priceScore: 60,
    satisfactionRate: 68,
  },
  {
    id: 5,
    name: "漓江花园酒店",
    type: "luxury",
    overallScore: 4.0,
    creditScore: 78,
    creditLevel: "normal",
    warningCount: 2,
    complaintRate: 3.2,
    serviceScore: 80,
    facilityScore: 82,
    cleanScore: 75,
    priceScore: 78,
    satisfactionRate: 79,
  },
  {
    id: 6,
    name: "桂林喜来登酒店",
    type: "luxury",
    overallScore: 4.7,
    creditScore: 92,
    creditLevel: "excellent",
    warningCount: 0,
    complaintRate: 0.8,
    serviceScore: 93,
    facilityScore: 90,
    cleanScore: 95,
    priceScore: 88,
    satisfactionRate: 92,
  },
  {
    id: 7,
    name: "榕湖客栈",
    type: "budget",
    overallScore: 3.2,
    creditScore: 55,
    creditLevel: "risk",
    warningCount: 5,
    complaintRate: 8.5,
    serviceScore: 55,
    facilityScore: 60,
    cleanScore: 50,
    priceScore: 65,
    satisfactionRate: 58,
  },
  {
    id: 8,
    name: "桂林万达文华酒店",
    type: "luxury",
    overallScore: 4.3,
    creditScore: 86,
    creditLevel: "good",
    warningCount: 1,
    complaintRate: 1.8,
    serviceScore: 87,
    facilityScore: 85,
    cleanScore: 88,
    priceScore: 84,
    satisfactionRate: 86,
  },
];

// 获取酒店列表
const fetchMerchantList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      hotelName: searchForm.name || undefined,
      type: searchForm.type || undefined,
      creditLevel: searchForm.creditLevel || undefined,
      sortOrder: sortOrder.value
    };

    const result = await axios.get("/admin/hotels/credits", { params });
    
    if (result.code === 200 && result.data) {
      merchantList.value = result.data.records || [];
      total.value = result.data.total || 0;
      
      // 更新统计数据
      if (result.data.stats) {
        updateStats(result.data.stats);
      } else {
        updateStatsByMockData(merchantList.value);
      }
    } else {
      // 使用测试数据
      useFilteredMockData();
    }
  } catch (error) {
    console.error("获取酒店列表失败：", error);
    ElMessage.error("获取酒店列表失败，使用测试数据");
    
    // 使用测试数据
    useFilteredMockData();
  } finally {
    loading.value = false;
  }
};

// 使用过滤后的测试数据
const useFilteredMockData = () => {
  // 根据搜索条件筛选数据
  let filteredData = mockData.filter((item) => {
    let match = true;
    if (searchForm.name) {
      match = match && item.name.includes(searchForm.name);
    }
    if (searchForm.type) {
      match = match && item.type === searchForm.type;
    }
    if (searchForm.creditLevel) {
      match = match && item.creditLevel === searchForm.creditLevel;
    }
    return match;
  });

  // 更新统计数据
  updateStatsByMockData(filteredData);

  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  merchantList.value = filteredData.slice(start, end);
  total.value = filteredData.length;

  // 排序
  sortMerchantList();
};

// 更新统计数据（使用后端返回的统计）
const updateStats = (stats) => {
  ratingStats.value = [
    {
      label: "平均评分",
      value: stats.avgScore.toFixed(1),
      icon: "fas fa-star",
      color: "#ffd700",
    },
    {
      label: "优秀酒店",
      value: stats.excellentCount,
      icon: "fas fa-crown",
      color: "#ff9900",
    },
    {
      label: "警告酒店",
      value: stats.warningCount,
      icon: "fas fa-exclamation-triangle",
      color: "#ff4949",
    },
    {
      label: "待整改",
      value: stats.needImproveCount,
      icon: "fas fa-tools",
      color: "#409eff",
    },
  ];
};

// 使用测试数据更新统计信息
const updateStatsByMockData = (data) => {
  const excellentCount = data.filter(
    (item) => item.creditLevel === "excellent",
  ).length;
  const warningCount = data.filter(
    (item) => item.warningCount > 0,
  ).length;
  const needImproveCount = data.filter((item) =>
    ["poor", "risk"].includes(item.creditLevel),
  ).length;
  const avgScore = data.length > 0 ? 
    (data.reduce((sum, item) => sum + item.overallScore, 0) / data.length).toFixed(1) : "0.0";

  ratingStats.value = [
    {
      label: "平均评分",
      value: avgScore,
      icon: "fas fa-star",
      color: "#ffd700",
    },
    {
      label: "优秀酒店",
      value: excellentCount,
      icon: "fas fa-crown",
      color: "#ff9900",
    },
    {
      label: "警告酒店",
      value: warningCount,
      icon: "fas fa-exclamation-triangle",
      color: "#ff4949",
    },
    {
      label: "待整改",
      value: needImproveCount,
      icon: "fas fa-tools",
      color: "#409eff",
    },
  ];
};

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1;
  fetchMerchantList();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    name: "",
    type: "",
    creditLevel: "",
  });
  handleSearch();
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchMerchantList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchMerchantList();
};

// 获取评分颜色
const getScoreColor = (score) => {
  if (score >= 90) return "#67c23a";
  if (score >= 80) return "#409eff";
  if (score >= 60) return "#e6a23c";
  return "#f56c6c";
};

// 获取信用评分颜色
const getCreditScoreColor = (score) => {
  if (score >= 90) return "#67c23a";
  if (score >= 80) return "#409eff";
  if (score >= 60) return "#e6a23c";
  return "#f56c6c";
};

// 获取信用等级标签类型
const getCreditLevelTag = (level) => {
  const typeMap = {
    excellent: "success",
    good: "primary",
    normal: "",
    poor: "warning",
    risk: "danger",
  };
  return typeMap[level];
};

// 获取信用等级标签文本
const getCreditLevelLabel = (level) => {
  const labelMap = {
    excellent: "优秀",
    good: "良好",
    normal: "一般",
    poor: "较差",
    risk: "风险",
  };
  return labelMap[level];
};

// 获取酒店类型标签类型
const getMerchantTypeTag = (type) => {
  const typeMap = {
    budget: "info",
    business: "primary",
    luxury: "success",
    resort: "warning",
  };
  return typeMap[type];
};

// 获取酒店类型标签文本
const getMerchantTypeLabel = (type) => {
  const labelMap = {
    budget: "经济型",
    business: "商务型",
    luxury: "豪华型",
    resort: "度假型",
  };
  return labelMap[type];
};

// 评分调整
const handleRating = (row) => {
  currentHotel.value = row;
  Object.assign(ratingForm, {
    serviceScore: row.serviceScore,
    facilityScore: row.facilityScore,
    cleanScore: row.cleanScore,
    priceScore: row.priceScore,
    reason: "",
  });
  ratingDialogVisible.value = true;
};

// 提交评分调整
const submitRating = async () => {
  if (!ratingFormRef.value) return;
  
  try {
    const valid = await ratingFormRef.value.validate();
    if (valid) {
      const ratingData = {
        hotelId: currentHotel.value.id,
        serviceScore: ratingForm.serviceScore,
        facilityScore: ratingForm.facilityScore,
        cleanScore: ratingForm.cleanScore,
        priceScore: ratingForm.priceScore,
        reason: ratingForm.reason
      };

      try {
        const res = await axios.post("/admin/hotels/credits/adjust", ratingData);
        
        if (res.code === 200) {
          ElMessage.success("评分调整成功");
          ratingDialogVisible.value = false;
          fetchMerchantList();
        } else {
          // 如果后端API调用失败，使用测试数据进行模拟
          simulateRatingAdjustment();
        }
      } catch (error) {
        console.error("评分调整失败：", error);
        ElMessage.error("评分调整失败，使用模拟数据");
        
        // 模拟评分调整成功
        simulateRatingAdjustment();
      }
    }
  } catch (error) {
    console.error("表单验证失败：", error);
  }
};

// 模拟评分调整
const simulateRatingAdjustment = () => {
  // 在本地数据中更新该酒店的评分
  const hotel = merchantList.value.find(item => item.id === currentHotel.value.id);
  if (hotel) {
    hotel.serviceScore = ratingForm.serviceScore;
    hotel.facilityScore = ratingForm.facilityScore;
    hotel.cleanScore = ratingForm.cleanScore;
    hotel.priceScore = ratingForm.priceScore;
    
    // 计算新的综合评分
    hotel.overallScore = ((
      hotel.serviceScore + 
      hotel.facilityScore + 
      hotel.cleanScore + 
      hotel.priceScore
    ) / 4 * 0.05).toFixed(1);
    
    ElMessage.success("评分调整成功（使用模拟数据）");
    ratingDialogVisible.value = false;
  }
};

// 发送警告
const handleWarning = (row) => {
  currentHotel.value = row;
  Object.assign(warningForm, {
    type: "",
    content: "",
    deadline: "",
  });
  warningDialogVisible.value = true;
};

// 提交警告
const submitWarning = async () => {
  if (!warningFormRef.value) return;
  
  try {
    const valid = await warningFormRef.value.validate();
    if (valid) {
      const warningData = {
        hotelId: currentHotel.value.id,
        warningType: warningForm.type,
        content: warningForm.content,
        deadline: warningForm.deadline
      };

      try {
        const res = await axios.post("/admin/hotels/credits/warning", warningData);
        
        if (res.code === 200) {
          ElMessage.success("警告发送成功");
          warningDialogVisible.value = false;
          fetchMerchantList();
        } else {
          // 如果后端API调用失败，使用测试数据进行模拟
          simulateWarning();
        }
      } catch (error) {
        console.error("警告发送失败：", error);
        ElMessage.error("警告发送失败，使用模拟数据");
        
        // 模拟警告发送成功
        simulateWarning();
      }
    }
  } catch (error) {
    console.error("表单验证失败：", error);
  }
};

// 模拟发送警告
const simulateWarning = () => {
  // 在本地数据中更新该酒店的警告次数
  const hotel = merchantList.value.find(item => item.id === currentHotel.value.id);
  if (hotel) {
    hotel.warningCount += 1;
    
    // 如果警告次数过多，可能会影响信用等级
    if (hotel.warningCount >= 3 && hotel.creditLevel !== 'risk') {
      // 降低信用等级
      const levels = ['excellent', 'good', 'normal', 'poor', 'risk'];
      const currentIndex = levels.indexOf(hotel.creditLevel);
      if (currentIndex < levels.length - 1) {
        hotel.creditLevel = levels[currentIndex + 1];
        hotel.creditScore = Math.max(50, hotel.creditScore - 10);
      }
    }
    
    ElMessage.success("警告发送成功（使用模拟数据）");
    warningDialogVisible.value = false;
  }
};

// 处罚
const handlePunishment = (row) => {
  currentHotel.value = row;
  Object.assign(punishmentForm, {
    type: "",
    amount: 0,
    duration: 1,
    reason: "",
    description: "",
  });
  punishmentDialogVisible.value = true;
};

// 提交处罚
const submitPunishment = async () => {
  if (!punishmentFormRef.value) return;
  
  try {
    const valid = await punishmentFormRef.value.validate();
    if (valid) {
      const punishmentData = {
        hotelId: currentHotel.value.id,
        punishmentType: punishmentForm.type,
        reason: punishmentForm.reason,
        description: punishmentForm.description
      };

      // 添加特定处罚类型的额外数据
      if (punishmentForm.type === "fine") {
        punishmentData.amount = punishmentForm.amount;
      }
      if (['booking_restriction', 'suspension'].includes(punishmentForm.type)) {
        punishmentData.duration = punishmentForm.duration;
      }

      try {
        const res = await axios.post("/admin/hotels/credits/punish", punishmentData);
        
        if (res.code === 200) {
          ElMessage.success("处罚提交成功");
          punishmentDialogVisible.value = false;
          fetchMerchantList();
        } else {
          // 如果后端API调用失败，使用测试数据进行模拟
          simulatePunishment();
        }
      } catch (error) {
        console.error("处罚提交失败：", error);
        ElMessage.error("处罚提交失败，使用模拟数据");
        
        // 模拟处罚提交成功
        simulatePunishment();
      }
    }
  } catch (error) {
    console.error("表单验证失败：", error);
  }
};

// 模拟处罚
const simulatePunishment = () => {
  // 在本地数据中更新该酒店的信用等级和评分
  const hotel = merchantList.value.find(item => item.id === currentHotel.value.id);
  if (hotel) {
    // 处罚会显著降低信用评分和信用等级
    const levelReduction = {
      'warning': 5,
      'fine': 10,
      'booking_restriction': 15,
      'suspension': 20,
      'termination': 30
    };
    
    const reduction = levelReduction[punishmentForm.type] || 10;
    hotel.creditScore = Math.max(0, hotel.creditScore - reduction);
    
    // 更新信用等级
    if (hotel.creditScore >= 90) {
      hotel.creditLevel = 'excellent';
    } else if (hotel.creditScore >= 80) {
      hotel.creditLevel = 'good';
    } else if (hotel.creditScore >= 60) {
      hotel.creditLevel = 'normal';
    } else if (hotel.creditScore >= 40) {
      hotel.creditLevel = 'poor';
    } else {
      hotel.creditLevel = 'risk';
    }
    
    ElMessage.success("处罚提交成功（使用模拟数据）");
    punishmentDialogVisible.value = false;
  }
};

// 切换排序顺序
const toggleSortOrder = (order) => {
  sortOrder.value = order;
  sortMerchantList();
};

// 排序酒店列表
const sortMerchantList = () => {
  merchantList.value.sort((a, b) => {
    const factor = sortOrder.value === "asc" ? 1 : -1;
    return (a.creditScore - b.creditScore) * factor;
  });
};

// 导出数据
const exportCreditData = () => {
  // 创建一个工作簿
  const wb = XLSX.utils.book_new();
  
  // 准备导出数据
  const exportData = merchantList.value.map(item => ({
    '酒店ID': item.id,
    '酒店名称': item.name,
    '酒店类型': getMerchantTypeLabel(item.type),
    '综合评分': item.overallScore,
    '信用评分': item.creditScore,
    '信用等级': getCreditLevelLabel(item.creditLevel),
    '警告次数': item.warningCount,
    '投诉率': item.complaintRate + '%',
    '客房服务评分': item.serviceScore,
    '客房设施评分': item.facilityScore,
    '卫生清洁评分': item.cleanScore,
    '性价比评分': item.priceScore,
    '客户满意度': item.satisfactionRate + '%'
  }));
  
  // 创建工作表
  const ws = XLSX.utils.json_to_sheet(exportData);
  
  // 设置列宽
  const colWidths = [
    { wch: 8 },  // 酒店ID
    { wch: 20 }, // 酒店名称
    { wch: 10 }, // 酒店类型
    { wch: 10 }, // 综合评分
    { wch: 10 }, // 信用评分
    { wch: 10 }, // 信用等级
    { wch: 10 }, // 警告次数
    { wch: 10 }, // 投诉率
    { wch: 15 }, // 客房服务评分
    { wch: 15 }, // 客房设施评分
    { wch: 15 }, // 卫生清洁评分
    { wch: 12 }, // 性价比评分
    { wch: 12 }  // 客户满意度
  ];
  
  ws['!cols'] = colWidths;
  
  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, '酒店评分与信用数据');
  
  // 生成Excel文件并下载
  const timestamp = new Date().getTime();
  const filename = `酒店评分与信用数据_${timestamp}.xlsx`;
  XLSX.writeFile(wb, filename);
  
  ElMessage.success(`已导出文件：${filename}`);
};

// 初始化
onMounted(() => {
  fetchMerchantList();
});
</script>

<style lang="scss" scoped>
.merchant-rating {
  padding: 20px;

  .statistics-row {
    margin-bottom: 20px;
  }

  .statistics-card {
    background-color: var(--el-bg-color);
    border-color: var(--el-border-color-light);
    transition: all 0.3s;

    .statistics-content {
      display: flex;
      align-items: center;
    }

    .statistics-icon {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 12px;

      i {
        color: var(--el-color-white);
        font-size: 24px;
      }
    }

    .statistics-info {
      .label {
        font-size: 14px;
        color: var(--el-text-color-secondary);
      }

      .value {
        font-size: 24px;
        font-weight: 600;
        margin-top: 4px;
        color: var(--el-text-color-primary);
      }
    }
  }

  .table-header-operations {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 8px 0;

    .el-button {
      background-color: var(--el-button-bg-color);
      border-color: var(--el-border-color);
      color: var(--el-text-color-regular);

      &.el-button--primary {
        background-color: var(--el-color-primary);
        border-color: var(--el-color-primary);
        color: var(--el-color-white);
      }
    }
  }

  :deep(.el-dialog) {
    background-color: var(--el-bg-color);
    border-color: var(--el-border-color);

    .el-dialog__header {
      border-bottom: 1px solid var(--el-border-color-light);
    }

    .el-dialog__body {
      padding-top: 10px;
      color: var(--el-text-color-primary);
    }

    .el-dialog__footer {
      border-top: 1px solid var(--el-border-color-light);
    }
  }

  :deep(.el-table) {
    background-color: var(--el-bg-color);

    th.el-table__cell {
      background-color: var(--el-bg-color-overlay);
    }

    .el-table__row {
      background-color: var(--el-bg-color);

      &:hover > td.el-table__cell {
        background-color: var(--el-bg-color-overlay);
      }
    }
  }

  .rule-detail {
    padding: 20px;
    background-color: var(--el-bg-color-overlay);
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  :deep(.rating-dialog) {
    .el-dialog__body {
      padding: 0 20px;
      max-height: calc(90vh - 120px);
      overflow: hidden;
    }
  }

  :deep(.el-dialog__wrapper) {
    overflow: hidden;
  }

  :deep(.el-overlay) {
    overflow: hidden;
  }

  .empty-state {
    padding: 40px 0;
  }

  .empty-text {
    font-size: 16px;
    color: var(--el-text-color-secondary);
    margin-top: 10px;
  }

  .empty-subtext {
    font-size: 14px;
    color: var(--el-text-color-placeholder);
    margin-top: 5px;
  }

  .mt-4 {
    margin-top: 16px;
  }
}
</style>
